from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from cart.cartser import CartSer
from cart.models import CartModel
from coures.courseser import CourseSer
from home.NavSer import CateSer
from utils.authentication import MyAuthentication


# Create your views here.
# 添加商品
class AddCart(APIView):
    authentication_classes = [MyAuthentication]
    def post(self,request):
        data=CartModel.objects.filter(user=request.data.get("user"),course=request.data.get("course")).first()
        if data:
            return Response({"msg":"该商品已经购买"})
        ser=CartSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"msg":"添加成功"})
        return Response({"msg":ser.errors})

# 展示所有课程
class CartFind(APIView):
    authentication_classes = [MyAuthentication]
    def get(self,request):
        pi=request.query_params.get("user_id")
        new=CartModel.objects.filter(is_del=0,user=pi)
        # 序列化器内需要连接课程表
        ne=CartSer(new,many=True)
        return Response({"data":ne.data})
# 根据iD删除
class CartDelete(APIView):
    authentication_classes = [MyAuthentication]
    def delete(self,request):
        id=request.query_params.get("course_id")
        CartModel.objects.get(id=id).delete()
        return Response({"msg":"删除成功"})
# 修改状态
class cartUp(APIView):
    authentication_classes = [MyAuthentication]
    def put(self,request):
        id=request.data.get("id")
        select=request.data.get("select")
        car=CartModel.objects.filter(id=id).first()
        if car:
            car.selected=select
            car.save()
            return Response({"msg":"修改成功"})
        return Response({"msg":"商品不存在"})

# 修改全选的状态
class cartAll(APIView):
    authentication_classes = [MyAuthentication]
    def put(self,request):
        user=request.data.get("user")
        select=request.data.get("select")
        car=CartModel.objects.filter(user=user)
        if car:
            for i in car:
                i.selected=select
                i.save()
            return Response("修改成功")
        return Response("不存在")

# 删除全选
class cartdel(APIView):
    authentication_classes = [MyAuthentication]
    def delete(self,request):
        user=request.query_params.get("user")
        cc=CartModel.objects.filter(user=user,selected=1).delete()
        if cc:
            return Response({"msg":"删除成功"})
        else:
            return Response({"msg":"删除失败"})